import _thread
import time
import random
from django.conf import settings

WAITING_TIME = 1
FundCache = {}

#os.environ.setdefault("DJANGO_SETTTINGS_MODULE", "project_name.settings")
#django.setup()

def _init():
    global FundCache
    global _global_dict
    _global_dict = None
    FundCache = {}
    return

def ReadFundInfoFromDB():
    global FundCache
    from fundinfo.models import FundName
    from django.conf import settings

    if FundCache.__contains__("fundCode") != True:
        FundCache["fundCode"] = {}

    if len(FundCache["fundCode"]) > 10:
        return
    
    funds = FundName.objects.all()
    for fund in funds:
        FundCache["fundCode"][fund.code] = fund
    return

def addCodeToDB(code):
    #print("get code", code)
    global FundCache
    ReadFundInfoFromDB()

    if FundCache["fundCode"].__contains__(code):
        #print("code exsit")
        return
    
    from fundinfo.models import FundName
    fund = FundName()
    fund.code = code
    fund.save()
    FundCache["fundCode"][code] = fund
    print("save code", code, "success.")


def fundRefreshTask(task):
    if task == None or task.name == 'refresh_all_quick':
        print('--------------refresh_all_quick--------------')
        from analysis.trading_analysis import TradingAnalysisTask
        trading = TradingAnalysisTask()
        trading.setAnalysisDir("./data/fundanalysis/")
        trading.setPriceDir("./data/fundprice/")
        trading.analyzeAllFund()

        from analysis.price_analysis import PriceAnalysisTask
        price = PriceAnalysisTask()
        price.setAnalysisDir("./data/fundanalysis/")
        price.setPriceDir("./data/fundprice/")
        price.analyzeAllFund()
    
    elif task.name == 'refresh_simple':
        print('--------------refresh_simple,' + task.argv + '--------------')
        from fundinfo.catch_fund_price import read_fundprice_by_ak
        read_fundprice_by_ak(task.argv)

    return

class TaskThread(object):
    isInit = False

    def readSimpleTask(self, a, b):
        time.sleep(WAITING_TIME)

        sleepTime = random.randint(1, 5)

        # __init__ will run 2 times, kill the second once
        from task.models import TmpTask

        ticks = time.time()
        if len(TmpTask.objects.all()) == 0:
            a = TmpTask()
            a.tick = ticks
            a.save()
        else:
            a = TmpTask.objects.all()[0]
            a.tick = ticks
            a.save()

        time.sleep(sleepTime)
        a = TmpTask.objects.all()[0]
        if a.tick == ticks:
            print("Find same ticks, I am exit.")
            return
        else:
            print("I can continue")

        fundRefreshTask(None)

        from task.models import SimpleTask
        while True:
            res = SimpleTask.objects.all()
            if len(res) == 0:
                time.sleep(2)
                continue
            task = res[0]

            print("get a task:", task.name, task.type, task.argv, task.lifecycle)

            fundRefreshTask(task)
            task.delete()
            time.sleep(10)

    def startTask(self):

        from strategies.mvavg import test
        test()

        if TaskThread.isInit == False:
            TaskThread.isInit = True
            _thread.start_new_thread(self.readSimpleTask, (0, 1))

thread = TaskThread()
thread.startTask()